/*
    nspire-gamekit - a simple homebrew game framework
    Copyright (C) 2011  Daniel Tang

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <os.h>
#include "file.h"
#define MAX_FILE_PATH_LENGTH 100 //ploaderhook.c in ndless defines it as 100 so we will too
#define MIN(x,y)            ((x) < (y) ? (x) : (y))

static char savedFilePath[MAX_FILE_PATH_LENGTH] = { 0 };

int gameSetCurrentDir(char *exec) {
    char base[MAX_FILE_PATH_LENGTH+1];
    if (savedFilePath[0] != 0) return -1;
    
    //Check if basename() worked
    if (basename(exec, base, MAX_FILE_PATH_LENGTH)) return -1; 
    //Check if we successfully saved our current working directory
    if (NU_Current_Dir("A:\\", savedFilePath)) return -1;
    //Finally, check if we successfully set our working directory
    NU_Set_Current_Dir(base);
    return 0;
}

int basename(char* filename, char* buff, NGKSizeInt maxlen) {
    char *current = filename;
    // We calculate basename for the path
    current += strlen(filename) - 1; //Ignore a trailing slash
    
    while (*current != '/') {
        if (current > filename) current--; else break;
    }
    
    if (current > filename) {
        strncpy(buff, filename, (size_t)MIN(maxlen, current-filename));
        buff[MIN(maxlen, current-filename)] = 0;
        return 0;
    } else {
        return -1;
    }
}

void gameRestoreCurrentDir() {
    if (savedFilePath[0] == 0) return;
    NU_Set_Current_Dir(savedFilePath);
}
